package designpattern.command.stringeditor.command;

import designpattern.command.stringeditor.model.StringBuf;

/**
 * 替换命令：替换从指定位置开始的字符串
 * 命令格式：r pos 'string'
 */
public class ReplaceCommand implements CanUndoCommand {
    
    private StringBuf stringBuf;
    private int start;
    private String replacement;
    private String originalText;

    public ReplaceCommand(StringBuf stringBuf, int start, String replacement) {
        this.stringBuf = stringBuf;
        this.start = start;
        this.replacement = replacement;
    }

    public static Command create(StringBuf stringBuf, int start, String replacement) {
        return new ReplaceCommand(stringBuf, start, replacement);
    }

    @Override
    public void execute() {
        originalText = stringBuf.replace(start, replacement);
    }

    @Override
    public void undo() {
        // 撤销替换操作，恢复原始文本
        stringBuf.replace(start, originalText);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((replacement == null) ? 0 : replacement.hashCode());
        result = prime * result + start;
        return result;
    }

    @Override
    public String toString() {
        return "ReplaceCommand [start=" + start + ", replacement=" + replacement + "]";
    }
}